<template>
  <view class="container">
    <!-- 商品图片 -->
	<view class="image">
		<image :src="productDetail.img"  mode="scaleToFill"></image>
	<!-- <image src="../../static/userbackground.png" class="product-image"></image> -->
	</view>
    

    <!-- 商品信息 -->
    <view class="product-info">
      <view class="product-name">{{ productDetail.name }}</view>
      <view class="product-description">{{ productDetail.description }}</view>
      <view class="product-prices">
        <text class="product-discount-price" v-if="productDetail.discount_price">￥{{ productDetail.discount_price }}</text>
        <text class="product-original-price" v-if="productDetail.discount_price">￥{{ productDetail.original_price }}</text>
        <text class="product-original-price2" v-else>￥{{ productDetail.original_price }}</text>
      </view>
      <!-- <view class="product-stock">库存: {{ productDetail.stock }}</view> -->
    </view>

    <!-- 商品导航 -->
    <view class="product-navigation">
      <navigator url="/pages/index/index" class="nav-item" @click="navigateToIndex">
        <image src="/static/icon/shouye.png" class="nav-icon"></image>
        <text class="nav-text">首页</text>
      </navigator>
      <view class="nav-item" @click="openNewsDialog">
        <image src="/static/icon/My.png" class="nav-icon"></image>
        <text class="nav-text">资讯</text>
      </view>
      <navigator url="/pages/cart/cart" class="nav-item" @click="navigateToCart">
        <image src="/static/icon/gouwuche.png" class="nav-icon"></image>
        <text class="nav-text">购物车</text>
      </navigator>
      <view class="action-buttons">
        <view v-if="state" @click="openDialog" class="buy-now-button">立即购买</view>
        <view v-else class="out-of-stock">无预约排期</view>
      </view>
    </view>
	<!-- 对话框背景遮罩 -->
			<view v-if="isDialogVisible" class="mask" @click="closeDialog"></view>
	
			<!-- 对话框 -->
			<view v-if="isDialogVisible" class="dialog">
				<view class="dialog-content">
					<view class="product-info2">
						<image :src="productDetail.img" class="product-image" />
						<view class="product-details">
							<text class="product-name">{{ productDetail.name }}</text>
							<view class="product-prices2">
								<text class="product-discount-price" v-if="productDetail.discount_price">￥{{ productDetail.discount_price }}</text>
								<text v-if="productDetail.discount_price" class="product-original-price">￥{{ productDetail.original_price }}</text>
								<text v-else class="product-original-price2">￥{{ productDetail.original_price }}</text>
							</view>
						</view>
					</view>
					<view>
					  <text>请选择预约时间:</text>
					  <view v-for="(dateGroup, index) in formattedSlots" :key="index">
					    <text class="date-label">{{ formatDate(dateGroup[0].appointment_time) }}</text>
					    <view class="time-slot">
					      <view v-for="slot in dateGroup" :key="slot.id" @click="selectSlot(slot)"
					        :class="{'time-option': true, 'selected': selectedSlot && selectedSlot.id === slot.id}">
					        <text>{{ formatTime(slot.appointment_time) }}</text>
					      </view>
					    </view>
					  </view>
					</view>
	<!-- 				<view class="quantity-control">
						<button @click="decreaseQuantity">-</button>
						<view>{{ cartDialogProduct.quantity }}</view>
						<button @click="increaseQuantity">+</button>
					</view> -->
					<button @click="addProductToCart" class="add-to-cart-button">立即预约</button>
				</view>
			</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      productDetail: {},
      AppointmentslotDetail: [],
	  availableSlot:[],
      productId: '',
      isDialogVisible: false,
      state: true,
      newsDialogVisible: false,
	   selectedSlot: null, 
    };
  },
  onLoad(options) {
    this.productId = options.id;
    this.fetchProductDetail();
    this.fetchAppointmentslotDetail();
  },
  computed: {
    formattedSlots() {
      const slotsMap = {};
      this.availableSlot.forEach(slot => {
        const date = this.formatDate(slot.appointment_time);
        if (!slotsMap[date]) {
          slotsMap[date] = [];
        }
        slotsMap[date].push(slot);
      });
      return Object.values(slotsMap);
    }
  },
  methods: {
    fetchProductDetail() {
      uni.request({
        url: `http://localhost:8887/Service/selectService?id=${this.productId}`, 
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200 && res.data.success) {
            this.productDetail = res.data.data;
            this.productDetail.img = res.data.data.img.replace(/&#34;/g, '');
            this.fetchAppointmentslotDetail();
          } else {
            uni.showToast({
              title: '获取商品详情失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
   fetchAppointmentslotDetail() {
     uni.request({
       url: `http://localhost:8887/Appointmentslot/selectservice_id?service_id=${this.productId}`, 
       method: 'GET',
       success: (res) => {
         if (res.data.code === 200) {
           this.AppointmentslotDetail = res.data.data;
           console.log(this.AppointmentslotDetail);
           // 筛选所有可预约的时间段
           this.availableSlot = this.AppointmentslotDetail.filter(slot => slot.state === "可预约");
           
           if (this.availableSlot.length > 0) {
             this.state = true;
           } else {
             this.state = false;
           }
         } else {
           uni.showToast({
             title: '获取预约时间段详情失败',
             icon: 'none',
             duration: 2000
           });
         }
       },
       fail: () => {
         uni.showToast({
           title: '网络请求失败',
           icon: 'none',
           duration: 2000
         });
       }
     });
   },
   addProductToCart() {
       if (this.selectedSlot && this.productDetail) {
         // 构建传递给 servicesettlement 页面的参数
         const params = {
           service_id: this.productDetail.id,
           appointment_id: this.selectedSlot.id
         };
   	console.log('124312:', params);
         // 跳转到 servicesettlement 页面，并传递参数
         uni.navigateTo({
           url: `/pages/servicesettlement/servicesettlement?product_id=${params.product_id}&appointment_id=${params.appointment_id}`,
         });
       } else {
         uni.showToast({
           title: '请选择商品和预约时间',
           icon: 'none',
           duration: 2000
         });
       }
     },
	formatDate(dateString) {
	    const date = new Date(dateString);
	    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	  },
	  formatTime(dateString) {
	    const date = new Date(dateString);
	    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
	  },
	  selectSlot(slot) {
	    this.selectedSlot = slot;
	  },
	addToCart(product) {
	  this.isDialogVisible = true;
	},
    openDialog() {
      if (this.productDetail.state === "无库存") {
        uni.showToast({
          title: '该商品无库存',
          icon: 'none',
          duration: 2000
        });
      } else {
        this.isDialogVisible = true;
        this.productDetail = {
          ...this.productDetail
        };
      }
    },
    closeDialog() {
      this.isDialogVisible = false;
    },
    navigateToIndex() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
	openNewsDialog(){
		uni.makePhoneCall({
		  phoneNumber: '15359369660' // 仅为示例
		});
	},
    navigateToCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      });
    },
    confirmPurchase() {
      uni.showToast({
        title: '立即购买成功',
        icon: 'success',
        duration: 2000
      });
      const productData = JSON.parse(JSON.stringify(this.productDetail));
      uni.navigateTo({
        url: '/pages/settlement2/settlement2?product=' + encodeURIComponent(JSON.stringify(productData)),
      });
    },
  }
};
</script>

<style>
/* 全局样式 */
.container {
  padding: 10px;
}
.image{
	width: 100%;
	 height: 250px;
}
.image>image{
	width: 100%;
	height: 250px;
}

.product-info {
	display: flex;
	width: 100%;
	flex-direction: column;
		margin-bottom: 20px;
		text-align: left;
	}

	.product-name {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 10px;
		 text-align: left;
		 width: 100%;
	}

	.product-description {
		 width: 100%;
		font-size: 14px;
		color: #666;
		margin-bottom: 10px;
		 text-align: left;
	}

	.product-prices {
		 width: 100%;
		font-size: 16px;
		color: #333;
		margin-bottom: 10px;
		 text-align: left;
	}

	.product-original-price {
		text-decoration: line-through;
		font-size: 14px;
		 text-align: left;
	}

	.product-original-price2 {
		color: red;
		font-size: 20px;
		font-weight: bold;
	}

	.product-discount-price {
		color: red;
		font-weight: bold;
		font-size: 20px;
	}

	.product-stock {
		font-size: 14px;
		 width: 100%;
		color: #666;
		 text-align: left;
	}
/* 商品导航栏 */
.product-navigation {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #333;
  width: 25%;
}

.nav-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 5px;
}

.nav-text {
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
}

.buy-now-button,
.out-of-stock {
  flex: 1;
  margin: 0 15px;
  text-align: center;
  border-radius: 25px;
  font-size: 16px;
  padding: 9px 10px;
}

.buy-now-button {
  background-color: #e4393c;
  color: white;
  border-radius: 11px ;
}

.out-of-stock {
  background-color: #ccc;
  color: white;
}

/* 对话框样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.dialog {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  z-index: 1001;
}

.dialog-content {
  display: flex;
  flex-direction: column;
}

/* .product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
} */

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
}

.product-details {
	height: 100px;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding-left: 10px;
flex: 1;
}

.product-name {
font-size: 20px;
font-weight: bold;
color: #333;
margin-bottom: 10px;
}

.product-prices {
font-size: 16px;
color: #666;
}

.quantity-control {
display: flex;
align-items: center;
margin-bottom: 20px;
}

.quantity-control button {
background-color: #f0f0f0;
color: #333;
border: none;
padding: 8px 12px;
border-radius: 8px;
font-size: 18px;
margin: 0 8px;
}

.buy-now-button3 {
background-color: #e4393c;
color: white;
padding: 12px 18px;
border-radius: 16px;
font-size: 18px;
width: 100%;
}

/* 资讯弹窗 */
.news-dialog {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1002;
display: flex;
justify-content: center;
align-items: center;
}

.news-dialog-content {
background-color: #fff;
padding: 20px;
border-radius: 10px;
text-align: center;
}

.news-dialog-content button {
background-color: #e4393c;
color: white;
padding: 10px 15px;
border-radius: 11px;
margin-top: 10px;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
.dialog {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 1001;
}
/* .dialog-content {
  padding: 20px;
} */
.product-info2 {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.quantity-control {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.quantity-control button {
  margin: 0 10px;
}
.add-to-cart-button {
  width: 100%;
  background-color: #e4393c;
  color: white;
  text-align: center;
  padding: 10px;
  border: none;
  outline: none;
  margin-top: 10px;
  
}
.no-more {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  color: #999;
  font-size: 16px;
}
.date-label {
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 5px;
}
.time-slot {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* Adjust the gap between time options */
}
.time-option {
  padding: 8px 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  background-color: #f0f0f0; /* Light background for better contrast */
}
.time-option.selected {
  background-color: #007aff;
  color: white;
}
.time-option:hover {
  background-color: #ebebeb;
}
</style>